import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import Home from '@/views/layout/HomeView'
import Category from '@/views/layout/CategoryView'
import User from '@/views/layout/UserView'
import Cart from '@/views/layout/CartView'
import store from '@/store'

const Login = () => import('@/views/login')
const MyOrder = () => import('@/views/myorder')
const Search = () => import('@/views/search')
const SearchList = () => import('@/views/search/list')
const Pay = () => import('@/views/pay')
const ProDetail = () => import('@/views/prodetail')

Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    redirect: '/home',
    name: 'Layout',
    component: Layout,
    children: [
      {
        path: '/home', name: 'home', component: Home
      },
      {
        path: '/category', component: Category
      },
      {
        path: '/user', component: User
      },
      {
        path: '/cart', component: Cart
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/search',
    name: 'Search',
    component: Search
  },
  {
    path: '/searchlist',
    name: 'ListIndex',
    component: SearchList
  },
  {
    path: '/prodetail/:id',
    name: 'ProDetail',
    component: ProDetail
  },
  {
    path: '/myorder',
    name: 'MyOrder',
    component: MyOrder
  },
  {
    path: '/pay',
    name: 'PayIndex',
    component: Pay
  },
  {
    path: '*', // 会匹配所有路径
    name: 'ErrorPage',
    component: () => import('@/views/error')
  }

]
const router = new VueRouter({
  routes
})
const AUTH_URLS = ['/pay', '/myorder']

router.beforeEach((to, from, next) => {
  // ...
  const token = store.getters['user/token']
  console.log(token, to, from)
  // 不需要拦截
  if (!AUTH_URLS.includes(to.path)) {
    next()
    return
  }
  // 有token放行，无则拦截
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
